package com.hankol.community

import android.annotation.SuppressLint
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.activity.BaseActivity
import com.baselibrary.base.TabPagerAdapter
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.baselibrary.view.AppBarStateChangeListener
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.PulpitInfoBean
import com.hankol.community.bean.ShowShare2Bean
import com.hankol.community.databinding.ActivityPulpitHomeBinding
import com.hankol.community.fragment.PulpitHomeInfoFragment
import com.hankol.community.viewmodel.PulpitViewModel


/**
 * @description 讲坛主页
 * @author 关忆北、
 * @time 2022/5/5 10:36 上午
 */
@Route(path = ActivityRouter.COMMUNITY.COMMUNITY_PULPITHOME)
class PulpitHomeActivity : BaseActivity(), View.OnClickListener {
    private val mTableName = mutableListOf("详情", "目录")
    private var pulpitId: Long = 0//讲坛id
    private lateinit var mDataBinding: ActivityPulpitHomeBinding
    private lateinit var mViewModel: PulpitViewModel
    private var mFragment: MutableList<Fragment> = mutableListOf()
    private var mPulpitHomeInfoFragment: PulpitHomeInfoFragment? = null
    private var mCataloguePulFragment: PulpitHomeInfoFragment? = null
    private var mPulpitInfoBean: PulpitInfoBean? = null
    private var mShowSharePop: SharePopupWindow? = null
    val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)
    override fun getLayoutId(): Int {
        return R.layout.activity_pulpit_home
    }

    override fun init() {
        SensorsDataManager.instance.onCreateTime()
        SensorsDataManager.instance.setFormPagePos("讲坛")
        mDataBinding = getDataBinding<ActivityPulpitHomeBinding>()
        mViewModel = getActivityViewModelProvider(this).get(PulpitViewModel::class.java)
        mDataBinding.tabPulpitHome.setSelectedTabIndicatorHeight(0);
        intent.extras?.let { it ->
            try {
                if (ARouterUtils.parseParams(it, "pulpitId")[0].checkNotNull()) {
                    pulpitId = ARouterUtils.parseParams(it, "pulpitId")[0].toLong()
                }
            } catch (e: Exception) {
                pulpitId = 0
            }

            mViewModel.reqPulpitHome(pulpitId)
            mPulpitHomeInfoFragment = PulpitHomeInfoFragment()
            mCataloguePulFragment = PulpitHomeInfoFragment()
            if (mPulpitHomeInfoFragment.checkNotNull()) {
                mFragment.add(mPulpitHomeInfoFragment!!)
            }
            if (mCataloguePulFragment.checkNotNull()) {
                mFragment.add(mCataloguePulFragment!!)
            }
            mDataBinding.vpPulpitHome.adapter = TabPagerAdapter(supportFragmentManager).setFragments(mFragment).setData(mTableName)

            initListener()
            initObserve()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initObserve() {
        mViewModel.pulpitHomeLD.observe(this, Observer { pulpitData ->
            if (pulpitData != null) {
                this.mPulpitInfoBean = pulpitData
                mViewModel.reqPulpitList(pulpitId)//拉取视频列表数据
                mPulpitHomeInfoFragment?.setHomeView(pulpitData)
                mCataloguePulFragment?.setPay(pulpitData.isPay)
                mDataBinding.tabPulpitHome.setupWithViewPager(mDataBinding.vpPulpitHome)
                mViewModel.initTabView(this, mDataBinding.tabPulpitHome, mTableName)
                mDataBinding.tvPulpitHomeTitle.text = pulpitData.title
                mDataBinding.tvPulpitHomeTitleCopy.text = pulpitData.title
                mDataBinding.tvPulpitHomeAuthorName.text = pulpitData.userName
                mDataBinding.ivPulpitHomeConState.isSelected = pulpitData.favorited == 1
                mDataBinding.ivPulpitHomeConStateCopy.isSelected = pulpitData.favorited == 1
                mDataBinding.tvPulpitHomePrice.text = pulpitData.price.toString()
                mDataBinding.llPulpitHomeBottom.visibility = if (pulpitData.isPay == 1) View.GONE else View.VISIBLE
                mDataBinding.ivPulpitHomeLecture.text = "共${pulpitData.courseNum}讲 · ${NumberUtils.formatBigNum(pulpitData.allWatchNum.toString())}播放"
                GlideUtils.loadImg_101(applicationContext, pulpitData.icon.checkValue(), mDataBinding.ivPulpitHomeCover)
                BannerSizeUtil.setBannerSizeValue(mDataBinding.ivPulpitHomeCover, 347, 129)
                GlideUtils.loadUserHead(applicationContext, pulpitData.userIcon, mDataBinding.circlePulpitHomeAuthorHead)

                if (pulpitData.favoriteNum == 0) {
                    mDataBinding.llPulCollection.visibility = View.INVISIBLE
                } else {
                    mDataBinding.llPulCollection.visibility = View.VISIBLE
                    mDataBinding.tvPulpitHomeCollection.text = "${NumberUtils.formatBigNum(pulpitData.favoriteNum.toString())}收藏"
                    mDataBinding.hcHeadList.setData(pulpitData.favoriteUserIconList)
                }
            }
        })

        mViewModel.pulpitListLD.observe(this, Observer {
            mDataBinding.srlPulpitHome.finishRefresh()
            if (it.checkNotNull() && it.data.checkNotNull()) mCataloguePulFragment?.setHomeVideoListView(pulpitId, it.data!!, it.totalCount)
        })

        mViewModel.subscribeLiveData.observe(this, Observer {
            if (it) mDataBinding?.ivPulpitHomeConState?.isSelected = !mDataBinding.ivPulpitHomeConState.isSelected

        })

        mViewModel.unlockPulpitLD.observe(this, Observer {
            if (it) {
                mCataloguePulFragment?.mAdapter?.isLock(true)
                mCataloguePulFragment?.setPay(1)
                mDataBinding.llPulpitHomeBottom.visibility = View.GONE
                ToastUtils.showShort(applicationContext, "解锁成功")
            }
        })
        mViewModel.collectionLiveData.observe(this, Observer { it ->
            if (it) {
                val selected = mDataBinding.ivPulpitHomeConState.isSelected
                mDataBinding.ivPulpitHomeConState.isSelected = !selected
                mDataBinding.ivPulpitHomeConStateCopy.isSelected = !selected
                mPulpitInfoBean?.let {
                    if (mDataBinding.ivPulpitHomeConState.isSelected) {
                        it.favorited = 1
                        it.favoriteNum = it.favoriteNum + 1
                        mDataBinding.hcHeadList.setData(it.favoriteUserIconList?.let { it1 -> mViewModel.upUserIconList(it1) })
                    } else {
                        it.favorited = 0
                        it.favoriteNum = if (it.favoriteNum - 1 >= 0) it.favoriteNum - 1 else 0
                        mDataBinding.hcHeadList.setData(it.favoriteUserIconList?.let { it1 -> mViewModel.detOwnUserIconList(it1) })
                    }
                    mDataBinding.tvPulpitHomeCollection.text = "${NumberUtils.formatBigNum(it.favoriteNum.toString())}收藏"
                    mDataBinding.llPulCollection.visibility = if (it.favoriteNum == 0) View.INVISIBLE else View.VISIBLE
                }
            }
        })
    }

    fun initListener() {
        mDataBinding.tvPulpitHomeTitle.paint.isFakeBoldText = true
        mDataBinding.tvPulpitHomeTitleCopy.paint.isFakeBoldText = true
        mDataBinding.tvPulpitHomeAuthorName.paint.isFakeBoldText = true
        mDataBinding.imgTopShare.setOnClickListener(this)
        mDataBinding.ivPulpitHomeBack.setOnClickListener(this)
        mDataBinding.tvPulpitHomePay.setOnClickListener(this)
        mDataBinding.ivPulpitHomeConState.setOnClickListener(this)
        mDataBinding.ivPulpitHomeConStateCopy.setOnClickListener(this)

        mDataBinding.appBarLayout.addOnOffsetChangedListener(object : AppBarStateChangeListener() {
            override fun onStateChanged(appBarLayout: AppBarLayout?, state: State?, verticalOffset: Int) {
                when (state) {
                    State.EXPANDED -> {
                        //展开状态
                        mDataBinding.tvPulpitHomeTitleCopy.visibility = View.INVISIBLE
                        mDataBinding.ivPulpitHomeConStateCopy.visibility = View.INVISIBLE

                        mDataBinding.tvPulpitHomeTitle.visibility = View.VISIBLE
                        mDataBinding.ivPulpitHomeConState.visibility = View.VISIBLE
                    }
                    State.COLLAPSED -> {
                        //折叠状态
                        mDataBinding.tvPulpitHomeTitleCopy.visibility = View.VISIBLE
                        mDataBinding.ivPulpitHomeConStateCopy.visibility = View.VISIBLE

                        mDataBinding.tvPulpitHomeTitle.visibility = View.INVISIBLE
                        mDataBinding.ivPulpitHomeConState.visibility = View.INVISIBLE
                    }
                    else -> {
                        //中间状态
                        mDataBinding.tvPulpitHomeTitleCopy.visibility = View.INVISIBLE
                        mDataBinding.ivPulpitHomeConStateCopy.visibility = View.INVISIBLE

                        mDataBinding.tvPulpitHomeTitle.visibility = View.VISIBLE
                        mDataBinding.ivPulpitHomeConState.visibility = View.VISIBLE
                    }
                }
            }

        })

        mDataBinding.vpPulpitHome.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (position == 1) {
                    //滑动 or 点击 到目录列表
                    mPulpitInfoBean?.let {
                        SensorsDataManager.instance.forumVideoListClick(it.title, it.courseTopicTitle)
                    }
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}

        })

        mDataBinding.tabPulpitHome.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab) {
                mViewModel.changeTabSelect(this@PulpitHomeActivity, tab, true)
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                mViewModel.changeTabSelect(this@PulpitHomeActivity, tab, false)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })

        mDataBinding.srlPulpitHome.setEnableLoadMore(false);//是否启用上拉加载功能
        mDataBinding.srlPulpitHome.setOnRefreshListener {
            mViewModel.reqPulpitHome(pulpitId)
        }

    }

    override fun onPause() {
        super.onPause()
        mPulpitInfoBean?.let {
            SensorsDataManager.instance.browseForum(it.courseTopicTitle, it.title, SensorsDataManager.instance.getBrowseTime(), mCataloguePulFragment?.getProgress()!!)
        }
    }

    override fun onDestroy() {
        mPulpitInfoBean?.let {
            mViewModel.noticePulCollection(it.favorited == 1)
        }
        super.onDestroy()

    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.img_top_share -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    //分享弹窗
                    mPulpitInfoBean?.let {
                        mShowSharePop = mViewModel.showShare(columnDetail2showShare(it), this, communityHelp)
                    }
                }
            }
            R.id.iv_pulpitHome_back -> finish()
            R.id.iv_pulpitHome_conState,
            R.id.iv_pulpitHome_conState_copy ->
                mViewModel.reqCollection(!mDataBinding.ivPulpitHomeConState.isSelected, 5, pulpitId)
            R.id.tv_pulpitHome_pay -> {
                if (DoubleUtils.isFastDoubleClick()) return
                mPulpitInfoBean?.let {
                    SensorsDataManager.instance.unlockForumContentNow(it.title, it.courseTopicTitle, it.price)
                    mViewModel.reqUnlockPulpit(this, it.price, pulpitId)
                }
            }

        }
    }

    private fun columnDetail2showShare(bean: PulpitInfoBean): ShowShare2Bean {
        return ShowShare2Bean().apply {
            id = bean.id
            showType = 1
            cover = bean.cover
            title = bean.title.checkValue()
            content = bean.desc.checkValue()
            url = Constants.FORUM_DETAIL_SHARE_URL + id
        }
    }
}